<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { ElTable, ElMessage, ElMessageBox } from 'element-plus'
import { materialPageService, materialAddService, materialEditService, materialDeleteService, materialStatusEditService } from '@/api/material/material'
import { materialCategoryPageService } from '@/api/material/materialCategory'
import { materialBrandPageService } from '@/api/material/materialBrand'
import { vendorPageService } from '@/api/basic/vendor'
import { materialNameService } from '@/api/material/material'

// 商品接口
interface Material {
  id: number
  barcode: string //条码
  vendor: number //供应商
  name: string  //名称
  specification: string //规格
  unit: string //单位
  category: number //类别
  brand: number //品牌
  purchasePrice: number  //采购价
  sellingPrice: number //销售价
  status: number  //状态
}

// 数据表格
const tableData = ref<Material[]>([])
// 商品表单
const form = ref<Material>({});
// 搜索框
const searchData = ref('')
// 供应商选择器
const vendorSelect = ref('')
const vendorOptions = ref([]);
// 类别选择器
const categorySelect = ref('')
const categoryOptions = ref([]);
// 品牌选择器
const brandSelect = ref('')
const brandOptions = ref([]);
// 抽屉是否显示
const addDrawer = ref(false);
const updateDrawer = ref(false);
//分页数据模型
const pageNum = ref(1)//当前页
const pageSize = ref(10)//每页条数
const total = ref(20)//总条数

// 商品名称选择器
const MaterialNameSelect = ref('')
const MaterialNameOptions = ref([]);

// 监听供应商选择器变化，如变化则刷新可选择商品列表
watch(() => form.value.vendor, async (newVendor) => {
  if (newVendor) {
    try {
      form.value.material = ''
      MaterialNameOptions.value = []
      const result = await materialNameService({ vendorId: newVendor });
      MaterialNameOptions.value = result.map(item => ({
        label: item.name,
        value: item.id,
      }));
    } catch (error) {
      ElMessage.error("获取商品名称失败，请稍后再试");
    }
  } else {
    MaterialNameOptions.value = []; // 如果供应商清空，重置商品名称选项
  }
});

// 分页数据监听
watch([() => pageNum.value, () => pageSize.value], async () => {
  await getMaterial();
});

// 商品列表查询
const getMaterial = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    categoryId: categorySelect.value ? categorySelect.value : null,
    search: searchData.value ? searchData.value : null
  }
  let result = await materialPageService(params)
  tableData.value = result.records;
  total.value = result.total
}

// 挂载函数，渲染列表
onMounted(async () => {
  let materialCategory = await materialCategoryPageService()
  let materialBrand = await materialBrandPageService()
  let vendor = await vendorPageService()
  console.log(vendor)
  // 遍历返回的分类对象
  categoryOptions.value = materialCategory.map(item => ({
    label: item.name,
    value: item.id,
  }));
  // 遍历返回的品牌对象
  brandOptions.value = materialBrand.map(item => ({
    label: item.name,
    value: item.id,
  }));
  // 遍历返回的供应商对象
  vendorOptions.value = vendor.map(item => ({
    label: item.name,
    value: item.id,
  }));
  await getMaterial();
})

// 多选框数据处理
const multipleSelection = ref<Material[]>([])
const handleSelectionChange = (val: Material[]) => {
  multipleSelection.value = val
}

// 添加
const add = () => {
  form.value.status = 1;
  let params = form.value
  materialAddService(params).then(() => {
    ElMessage.success("添加成功")
    addDrawer.value = false
    form.value={}
    getMaterial()
  })
}

// 取消添加
const addCancel = () => {
  addDrawer.value = false
  form.value = {}
}

// 删除
const del = (row) => {
  let deleteIds = row.id
  let params = {
    ids: deleteIds,
  }
  console.log(params)
  materialDeleteService(params).then(() => {
    ElMessage.success("删除成功")
    getMaterial()
  })
}

// 批量删除
const deleteMultiple = () => {
  if (multipleSelection.value.length > 0) {
    // 显示确认对话框
    ElMessageBox.confirm(
      '是否确认删除?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      // 用户确认删除
      // 遍历数组获得只有id属性的数组，再将其转换为以','分割的字符换进行拼接
      let deleteIds = multipleSelection.value.map(material => material.id).join(',');
      let params = {
        ids: deleteIds,
      };
      materialDeleteService(params).then(() => {
        ElMessage.success("删除成功");
        getMaterial(); // 刷新列表数据
      }).catch(() => {
        ElMessage.error("删除失败");
      });
    }).catch(() => {
      // 用户取消删除
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
  } else {
    ElMessage.error("未选择数据");
  }
};

// 修改数据回显
const updateEcho = (row) => {
  const updateData = { ...row };
  updateDrawer.value = true
  const vendorKey = vendorOptions.value.find(option => option.label === updateData.vendor);
  const categoryKey = categoryOptions.value.find(option => option.label === updateData.category);
  const brandKey = brandOptions.value.find(option => option.label === updateData.brand);
  // 如果映射没数据，则将修改字段赋空值
  if (vendorKey) {
    updateData.vendor = vendorKey.value;
  }else {
    updateData.vendor = ''
  }
  if (categoryKey) {
    updateData.category = categoryKey.value;
  }else {
    updateData.category=''
  }
  if (brandKey) {
    updateData.brand = brandKey.value;
  }else {
    updateData.brand =''
  }
  form.value = updateData  // 数据回显
}

// 修改
const update = () => {
  let params = { ...form.value }
  console.log(params)
  materialEditService(params).then(() => {
    ElMessage.success("修改成功")
    updateDrawer.value = false
    getMaterial()
  })
}

// 取消修改
const updateCancel = () => {
  updateDrawer.value = false
  form.value = {}
}

//修改状态
const handleStatusChange = (row) => {
  // 获取状态变化后的值
  const newStatus = row.status
  const params = {
    ids: row.id,
    status: newStatus,
  };
  // 调用后端服务更新状态
  materialStatusEditService(params).then(() => {
    if (newStatus == 1) {
      ElMessage.success("启用成功");
    } else {
      ElMessage.success("禁用成功")
    }

  }).catch((error) => {
    ElMessage.error("状态更新失败");
    // 恢复为原来的状态
    row.status = !row.status;
  });
};

// 批量修改状态
const StatusMultiple = (status) => {
  if (multipleSelection.value.length > 0) {
    let ids = multipleSelection.value.map(material => material.id).join(',')
    let params = {
      ids: ids,
      status: status,
    }
    // 修改状态
    materialStatusEditService(params)
      .then(() => {
        if (status == 1) {
          multipleSelection.value.forEach((item) => {
            item.status = 1;
          })
          ElMessage.success("启用成功")

        } else {
          multipleSelection.value.forEach((item) => {
            item.status = 0;
          })
          ElMessage.success("禁用成功")
        }
      }).catch((e) => {
        console.log(e)
      }).catch((e) => {
        console.log(e)
      })
  } else {
    ElMessage.error("未选择数据")
  }
}

// 查找
const search = () => {
  getMaterial().then(() => {
    ElMessage.success("查询成功")
  })
}

// 重置
const reset = () => {
  searchData.value = ''
  categorySelect.value = ''
}

// 刷新
const refresh = () => {
  reset()
  getMaterial()
  ElMessage.success("刷新成功")
}

const rules = ref({
  barcode: [
    { required: true, message: '请输入商品条码', trigger: 'blur' },
    { min: 1, max: 20, message: '条码长度在1-20个字符之间', trigger: 'blur' }
  ],
  vendor: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 20, message: '名称长度在1-20个字符之间', trigger: 'blur' }
  ],
  specification: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择类别', trigger: 'change' }
  ],
  brand: [
    { required: true, message: '请选择品牌', trigger: 'change' }
  ],
  purchasePrice: [
    { required: true, message: '请输入采购价', trigger: 'blur' },
    { type: 'number', message: '采购价必须为数字', trigger: 'blur', transform: (value) => Number(value) },
    { type: 'number', min: 0, message: '采购价必须大于等于0', trigger: 'blur', transform: (value) => Number(value) }
  ],
  sellingPrice: [
    { required: true, message: '请输入销售价', trigger: 'blur' },
    { type: 'number', message: '销售价必须为数字', trigger: 'blur', transform: (value) => Number(value) },
    { type: 'number', min: 0, message: '销售价必须大于等于0', trigger: 'blur', transform: (value) => Number(value) }
  ]
})
</script>

<template>
  <el-form label-width="auto" class="form-style">
    <div class="form-group">
      <div class="form-item">
        <el-form-item label="类别:">
          <el-select v-model="categorySelect" placeholder="请选择类别">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
      <div class="form-item">
        <el-form-item label="商品信息:">
          <el-input v-model="searchData" placeholder="请输入条码、名称等信息"></el-input>
        </el-form-item>
      </div>
      <div class="form-item">
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </div>
    </div>
  </el-form>

  <div class="button-group">
    <el-button type="primary" @click="addDrawer = true">新增商品</el-button>
    <el-button plain @click="deleteMultiple">批量删除</el-button>
    <el-button @click="StatusMultiple(1)">启用</el-button>
    <el-button @click="StatusMultiple(0)">禁用</el-button>
    <el-button plain @click="refresh">刷新</el-button>
  </div>

  <div class="table-wrapper">
    <el-table border height="68vh" ref="multipleTableRef" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column label="操作" min-width="100">
        <template #default="row">
          <el-button link type="primary" @click="updateEcho(row.row)">编辑</el-button>
          <el-popconfirm title="确认删除?" @confirm='del(row.row)'>
            <template #reference>
              <el-button link type="primary">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
<!--      <el-table-column property="id" label="ID" show-overflow-tooltip />-->
      <el-table-column property="barcode" label="条码" show-overflow-tooltip />
      <el-table-column property="vendor" label="供应商" show-overflow-tooltip />
      <el-table-column property="name" label="名称" show-overflow-tooltip />
      <el-table-column property="specification" label="规格" show-overflow-tooltip />
      <el-table-column property="unit" label="单位" show-overflow-tooltip />
      <el-table-column property="category" label="类别" show-overflow-tooltip />
      <el-table-column property="brand" label="品牌" show-overflow-tooltip />
      <el-table-column property="purchasePrice" label="采购价" show-overflow-tooltip />
      <el-table-column property="sellingPrice" label="销售价" show-overflow-tooltip />
      <el-table-column property="status" label="状态">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>>
    </el-table>

    <!-- 新增表单 -->
    <el-drawer v-model="addDrawer" direction="rtl" :show-close="false" size="40%" title="新增商品">
      <el-form :model="form" :rules="rules" style="width: 80%" label-width="auto">
        <el-form-item label="条码:" prop="barcode">
          <el-input v-model="form.barcode" />
        </el-form-item>
        <el-form-item label="供应商:" prop="vendor">
          <el-select v-model="form.vendor" placeholder="请选择供应商">
            <el-option v-for="item in vendorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称:" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="规格:">
          <el-input v-model="form.specification" />
        </el-form-item>
        <el-form-item label="单位:">
          <el-input v-model="form.unit" />
        </el-form-item>
        <el-form-item label="类别:" prop="category">
          <el-select v-model="form.category" placeholder="请选择类别">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌:" prop="brand">
          <el-select v-model="form.brand" placeholder="请选择品牌">
            <el-option v-for="item in brandOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购价:" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" />
        </el-form-item>
        <el-form-item label="销售价:" prop="sellingPrice">
          <el-input v-model="form.sellingPrice" />
        </el-form-item>
        <el-button type="primary" @click="add">新增</el-button>
        <el-button @click="addCancel">取消</el-button>
      </el-form>
    </el-drawer>

    <!-- 编辑表单 -->
    <el-drawer v-model="updateDrawer" direction="rtl" :show-close="false" size="40%" title="编辑商品">
      <el-form :model="form" :rules="rules" style="width: 80%" label-width="auto">
        <el-form-item label="条码:" prop="barcode">
          <el-input v-model="form.barcode" />
        </el-form-item>
        <el-form-item label="供应商:" prop="vendor">
          <el-select v-model="form.vendor" placeholder="请选择供应商">
            <el-option v-for="item in vendorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称:" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="规格:">
          <el-input v-model="form.specification" />
        </el-form-item>
        <el-form-item label="单位:">
          <el-input v-model="form.unit" />
        </el-form-item>
        <el-form-item label="类别:" prop="category">
          <el-select v-model="form.category" placeholder="请选择类别">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌:" prop="brand">
          <el-select v-model="form.brand" placeholder="请选择品牌">
            <el-option v-for="item in brandOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购价:" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" />
        </el-form-item>
        <el-form-item label="销售价:" prop="sellingPrice">
          <el-input v-model="form.sellingPrice" />
        </el-form-item>
        <el-button type="primary" @click="update">修改</el-button>
        <el-button @click="updateCancel">取消</el-button>
      </el-form>
    </el-drawer>
  </div>

  <div class="example-pagination-block">
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" layout="prev, pager, next"
      :total="total" />
  </div>

</template>

<style scoped>
/* 第1行盒子-表单组件 */
.form-item {
  display: inline-block;
  /* 行内显示 */
  margin-right: 3vh;
}

/* 第1行盒子-表单组件-输入框 */
.form-item .el-form-item {
  width: 40vh;
}

/* 第2行组件 */
.button-group {
  margin-left: 3vh;
}

/* 第2行组件-按钮 */
.button-group .el-button {
  width: 12vh;
}

/* 第3行表格盒子 */
.table-wrapper {
  margin-left: 2vh;
  margin-top: 2vh;
}

/* 分页条盒子 */
.example-pagination-block {
  padding-left: 44%;
  margin-top: 1vh;
  /* 根据需要调整上边距 */
}
</style>